tinyMCEPopup.requireLangPack();

var templates = {
	"window.open" : "window.open('${url}','${target}','${options}')"
};

function tinyGadgets()
{
	
	this.mode = 'Maps';
	this.modeInitial = '';
	
	// Variables indiquant quels gadgets ont été initialisés
	this.youtubeInitialise = false;
	this.mapsInit = false;
	
	// Google Maps
	this.maps_map = null;
	this.maps_geocoder = null;
	this.maps_marker = null;
	this.maps_adresse = '';
	this.maps_initPoint = null;
	
}

tg = new tinyGadgets();

//-------------------
//----- Général -----
//-------------------
tg.inserer = function()
{
	
	var ed = tinyMCEPopup.editor, f = document.forms[0], nl = f.elements, v, args = {}, el;

	tinyMCEPopup.restoreSelection();
	
	// Fixes crash in Safari
	if (tinymce.isWebKit)
		ed.getWin().focus();
	
	var el = ed.selection.getNode();
	var modification = (el && el.nodeName == 'IMG');
	
	if(tg.mode != tg.modeInitial) {
		modification = false;
	}
	
	if(tg.mode == 'Maps')
	{
		args = {
			src: tinyMCEPopup.getWindowArg("plugin_url") + '/img/trans.gif',
			'class' : 'mceCpGadgetMaps',
			title : 'cpGadget',
			alt : tg.mode,
			options : tg.mapsInserer()
		};
		
		if(args.options == false) {
			tinyMCEPopup.close();
			return;
		}
		
		if(!modification)
		{
			args.width = '425';
			args.height = '350';
		}
		
	}
	else if(tg.mode == 'Youtube')
	{
		
		args = {
			src: tinyMCEPopup.getWindowArg("plugin_url") + '/img/trans.gif',
			'class' : 'mceCpGadgetYoutube',
			title : 'cpGadget',
			alt : tg.mode,
			options : tg.youtubeInserer()
		};
		
		if(args.options == false) {
			tinyMCEPopup.close();
			return;
		}

		if(!modification)
		{
			args.width = '548';
			args.height = '340';
		}
		
	}
	
	if (modification) {
		ed.dom.setAttribs(el, args);
	} else {		
		ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp_img" />', {skip_undo : 1});
		ed.dom.setAttribs('__mce_tmp_img', args);
		ed.dom.setAttrib('__mce_tmp_img', 'id', '');
		ed.undoManager.add();
	}

	tinyMCEPopup.close();
	
};

tg.changerMode = function(mode, param1, param2)
{
	$('#menuTypesGadgets>ul>li>a').removeClass('selectionne');
	$('#type'+mode).addClass('selectionne');
	$('div.paramsGadget').hide();
	$('#params'+mode).show();
	tg.mode = mode;
	
	if(mode == 'Maps')
		tg.initMaps(param1, param2);
	else if(mode == 'Youtube')
		tg.initYoutube();
	
};


// ----------------
// ----- Maps -----
// ----------------
tg.initMaps = function(params, adresse)
{
	
	// Éviter d'initialiser le gadget plusieurs fois
	if(this.mapsInit) {
		return;
	}
	
	this.mapsInit = true;
	
	var posInitiale = new google.maps.LatLng(-34.397, 150.644);
	var optionsMap = {
		zoom: 8,
		center: posInitiale,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	params = params || optionsMap;
	params.streetViewControl = false;
	
	this.maps_map = new google.maps.Map(document.getElementById("maps_conteneurMap"),params);
	this.maps_geocoder = new google.maps.Geocoder();
	
	$('#maps_formulaireRecherche').submit(function() {
		tg.mapsRecherche();
		return false;
	});

	if(adresse != '' && typeof(adresse) != 'undefined')
	{
		$('#maps_recherche_motcle').val(adresse);
		tg.mapsRecherche();
	}
	
};

tg.mapsRecherche = function()
{
	var obj = this;
	var adresse = $('#maps_recherche_motcle').val();
	
	if(adresse == '')
	{
		$('#maps_resultatsRecherche').html('<p class="erreur">Vous devez indiquer une adresse.</p>');
	}
	
	obj.maps_geocoder.geocode( { 'address': adresse }, function(results, status) {
		yoda = results;
		if(status == google.maps.GeocoderStatus.OK)
		{
			
			// Un seul résultat
			if(results.length == 1)
			{				
				$('#maps_resultatsRecherche').html('<p class="maps_unResultat">'+results[0].formatted_address+'</p>');
				obj.mapsAfficherResultat(results[0]);
			}
			// Plusieurs résultats
			else
			{
				$('#maps_resultatsRecherche').html('<p>Votre recherche a retourné plusieurs résultats:</p><ul></ul>');
				for(var i = 0; i < results.length; i++)
				{
					$('#maps_resultatsRecherche>ul').append('<li><a href="#">'+results[i].formatted_address+'</a></li>');
					$('#maps_resultatsRecherche>ul>li:last-child>a').data('googlemaps', results[i]).click(function() {
						obj.mapsAfficherResultat($(this).data('googlemaps'));
					});
				}
			}
			
		}
		else if(status == google.maps.GeocoderStatus.ZERO_RESULTS)
		{
			$('#maps_resultatsRecherche').html('<p class="erreur">Votre recherche n\'a donné aucun résultat.</p>');
		}
		else
		{
			$('#maps_resultatsRecherche').html('<p class="erreur">Impossible d\'effectuer la recherche ('+status+')</p>');
		}
		
	});

};

tg.mapsAfficherResultat = function(resultat)
{
	if(tg.maps_marker != null)
		tg.maps_marker.setMap(null);
	
	if(typeof(resultat.geometry.bounds) != 'undefined') {
		tg.maps_map.fitBounds(resultat.geometry.bounds);
	}
	tg.maps_map.setCenter(resultat.geometry.location);
    tg.maps_marker = new google.maps.Marker({
        map: tg.maps_map, 
        position: resultat.geometry.location
    });
    
    tg.maps_adresse = resultat.formatted_address;
    
    if(tg.maps_initPoint != null) {
    	tg.maps_map.setCenter(tg.maps_initPoint.center);
    	tg.maps_map.setZoom(tg.maps_initPoint.zoom);
    	tg.maps_initPoint = null;
    }
    
};

tg.mapsInserer = function()
{
	var q = tg.maps_adresse;
	var ll = tg.maps_map.getCenter().toUrlValue();
	var z = tg.maps_map.getZoom();
	var t = tg.maps_map.getMapTypeId();
	
	if(q == '') {
		return false;
	}
	
	return ll+'|'+z+'|'+t+'|'+q;
};

//-------------------
//----- Youtube -----
//-------------------

tg.initYoutube = function()
{
	if(!tg.youtubeInitialise)
	{
		$('#youtube_url').add('#youtube_similaires').add('#youtube_hd').change(function() {
			tg.youtubeApercu();
		});
		tg.youtubeInitialise = true;
	}
};

tg.youtubeApercu = function()
{
	
	var v = $('#youtube_url').val();
	if (v.match(/watch\?v=(.+)(.*)/)) {
		
		if($('#youtube_similaires').attr('checked')) {
			var similaires = '?rel=1';
		} else {
			var similaires = '?rel=0';
		}
		
		if($('#youtube_hd').attr('checked')) {
			var hd = '&hd=1';
		} else {
			var hd = '&hd=0';
		}
		
		var url = 'http://www.youtube.com/embed/' + v.match(/v=(.*)(.*)/)[0].split('=')[1];
		$('#youtube_apercu').html('<iframe title="YouTube video player" class="youtube-player" type="text/html" width="290" height="195" src="'+url+similaires+hd+'" frameborder="0"></iframe>');
	}
	
};

tg.youtubeInserer = function()
{
	
	var url = $('#youtube_url').val();
	if (url.match(/watch\?v=(.+)(.*)/)) {
		var idVideo = url.match(/v=(.*)(.*)/)[0].split('=')[1];
	} else {
		return false;
	}
	
	var similaires = $('#youtube_similaires').attr('checked') ? '1' : '0';
	var hd = $('#youtube_hd').attr('checked') ? '1' : '0';
	
	return similaires+'|'+hd+'|'+idVideo;
	
};

//--------------------------------------
//----- Initialisation de la popup -----
//--------------------------------------

function isGadgetElm(n) {
	return $(n).attr('title') == 'cpGadget';
};

tinyMCEPopup.onInit.add(function()
{
	
	var inst = tinyMCEPopup.editor;
	var elm = inst.selection.getNode();
	var action = "insert";
	
	if (elm != null && elm.nodeName == 'IMG' && isGadgetElm(elm))
		action = "update";

	if(action == 'update')
	{
	
		var options = $(elm).attr('options');
		
		// Modification d'un gadget Google Maps
		if($(elm).attr('alt') == 'Maps')
		{
			
			var virgule1 = options.indexOf(',');
			var barre1 = options.indexOf('|');
			var barre2 = options.indexOf('|',barre1+1);
			var barre3 = options.indexOf('|', barre2+1);
			
			var latitude = options.substr(0,virgule1);
			var longitude = options.substr(virgule1+1,barre1-virgule1-1);
			var zoom = options.substr(barre1+1, barre2-barre1-1);
			var type = options.substr(barre2+1, barre3-barre2-1);
			var adresse = options.substr(barre3+1);
			
			tg.maps_initPoint = {
				zoom: parseInt(zoom),
				center:new google.maps.LatLng(latitude, longitude)
			};
			
			tg.changerMode('Maps', {
				zoom: parseInt(zoom),
				center: new google.maps.LatLng(latitude, longitude),
				mapTypeId: type
			}, adresse);
			
			tg.modeInitial = 'Maps';
			
		}
		else if($(elm).attr('alt') == 'Youtube')
		{
			tg.changerMode('Youtube');
			
			var barre1 = options.indexOf('|');
			var barre2 = options.indexOf('|',barre1+1);
			
			var similaires = options.substr(0,barre1);
			var hd = options.substr(barre1+1, barre2-barre1-1);
			var idVideo = options.substr(barre2+1);
			
			$('#youtube_url').val('http://www.youtube.com/watch?v='+idVideo);
			if(similaires == '1') {
				$('#youtube_similaires').attr('checked', 'checked');
			}
			if(hd == '1') {
				$('#youtube_hd').attr('checked', 'checked');
			}
			tg.youtubeApercu();
			
			tg.modeInitial = 'Youtube';
			
		}
		
	}
	else
	{
		tg.changerMode('Maps');
	}
	
	$('#typeMaps').click(function() {tg.changerMode('Maps');});
	$('#typeYoutube').click(function() {tg.changerMode('Youtube');});
	
	$('#insert').click(tg.inserer);
	
});